//
//  Cliqset.m
//  cliqset
//
//  Created by David Hinson on 2/17/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "Cliqset.h"
#import "cliqsetAppDelegate.h"
#import "XMLReader.h"
#import "ParseEventXMLReader.h"
#import "ParseProfileXMLReader.h"
#import "ParseStatusXMLReader.h"
#import "ParsePendingRelationshipsXMLReader.h"
#import "ParseRelationshipXMLReader.h"
#import "ParseMessagesXMLReader.h"
#import "ParseQueryResultsXMLReader.h"

#import "EventThread.h"
#import "ContactsThread.h"
#import "ProfileThread.h"
#import "StatusThread.h"
#import "ProfileEventsThread.h"
#import "RelationshipsThread.h"
#import "MessageCountThread.h"
#import "MessagesThread.h"
#import "SentMessagesThread.h"
#import "RelationshipCountsThread.h"
#import "RelationshipRequestsThread.h"

@implementation Cliqset

@synthesize currentContact;
@synthesize currentType;
@synthesize currentField;
@synthesize currentFlag;
@synthesize isFavorite;

@synthesize currentStreet;
@synthesize currentLocality;
@synthesize currentRegion;
@synthesize currentPostalCode;
@synthesize currentCountry;

@synthesize currentContactRecord;

@synthesize currentRelationshipOffset;

@synthesize currentIndex;

#pragma mark ---- authentication ----

// For getting strings from Settings Bundle
NSString *kloginKey			= @"loginKey";
NSString *kpasswordKey		= @"passwordKey";

// Consumer key from cliqset
NSString *consumerKey       = @"your_consumer_key_here";

/*
 ** Global data used by both binary-to-base64 and base64-to-binary conversions
 */

static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"+/";

int encode(unsigned s_len, char *src, unsigned d_len, char *dst)
{
	unsigned triad;
	
	for (triad = 0; triad < s_len; triad += 3)
	{
		unsigned long int sr;
		unsigned byte;
		
		for (byte = 0; (byte<3)&&(triad+byte<s_len); ++byte)
		{
			sr <<= 8;
			sr |= (*(src+triad+byte) & 0xff);
		}
		
		sr <<= (6-((8*byte)%6))%6; /*shift left to next 6bit alignment*/
		
		if (d_len < 4) return 1; /* error - dest too short */
		
		*(dst+0) = *(dst+1) = *(dst+2) = *(dst+3) = '=';
		switch(byte)
		{
			case 3:
				*(dst+3) = base64[sr&0x3f];
				sr >>= 6;
			case 2:
				*(dst+2) = base64[sr&0x3f];
				sr >>= 6;
			case 1:
				*(dst+1) = base64[sr&0x3f];
				sr >>= 6;
				*(dst+0) = base64[sr&0x3f];
		}
		dst += 4; d_len -= 4;
	}
	
	return 0;
	
}

// Init Cliqset
-(Cliqset*)init {
	self = [super init];	
	return self;
}

// Authenticate the user
-(void)authenticate {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	myApp.loginString    = (NSMutableString*)[[NSUserDefaults standardUserDefaults] stringForKey:kloginKey];
	myApp.passwordString = (NSMutableString*)[[NSUserDefaults standardUserDefaults] stringForKey:kpasswordKey];

	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	NSMutableString *dataStr = (NSMutableString*)[@"" stringByAppendingFormat:@"%@:%@", myApp.loginString, myApp.passwordString];
	
	NSData *encodeData = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
	char encodeArray[512];
	memset(encodeArray,'\0', sizeof(encodeArray));
	
	// Base64 Encode username and password
	encode([encodeData length], (char *)[encodeData bytes], sizeof(encodeArray), encodeArray);	
	
	dataStr = [NSString stringWithCString:encodeArray length:strlen(encodeArray)];	
	myApp.authenticationString = [@"" stringByAppendingFormat:@"Basic %@", dataStr];
	
	myApp.isAuthenticated  = NO;
	myApp.isAuthenticating = YES;
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 0;
	connector.parent = self;
	
	// Create asyncronous request
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.cliqset.com/user/useridentifier"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData = [[NSMutableData data] retain];
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Do logout
-(void)logout {
	cliqsetAppDelegate* myApp            = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSUserDefaults *standardUserDefaults = (NSUserDefaults *)[NSUserDefaults standardUserDefaults];

	// Clear credentials fields
	[standardUserDefaults setObject:@"" forKey:kloginKey];
	[standardUserDefaults setObject:@"" forKey:kpasswordKey];
	
	myApp.loginString          = @"";
	myApp.passwordString       = @"";
	myApp.authenticationString = @"";
	
	// Reset current profile
	if (myApp.currentProfile) {
		[myApp.currentProfile release];
		myApp.currentProfile = nil;
	}
	
	[myApp flipSplashToFront];
	
	// Clear internal contacts table
	[myApp.contacts removeAllObjects];
	[myApp.notifications removeAllObjects];
	[myApp.toEvents removeAllObjects];
	[myApp.fromEvents removeAllObjects];
	[myApp.profileEvents removeAllObjects];
	[myApp.relationships removeAllObjects];
	
	// Clean the screen of contacts
	[myApp reloadContactsTable];
	
	// Clear the database
	[myApp.database saveContactsToDatabase];

	// Reset the timestamp
	[myApp.database resetTimestamp];
	
	[self authenticate];
}

// Is this an error?
-(BOOL)isError:(NSString*)dataStr {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([dataStr isEqualToString:@"Error 500"]) {
		[myApp addTextToLog:@"Server Error" withCaption:@"cliqset"];
		return YES;
	}
	if ([dataStr isEqualToString:@"Error 400"]) {
		[myApp addTextToLog:@"Bad Request" withCaption:@"cliqset"];
		return YES;
	}
	if ([dataStr isEqualToString:@"Error 401"]) {
		[myApp addTextToLog:@"Unauthorized" withCaption:@"cliqset"];
		return YES;
	}
	if ([dataStr isEqualToString:@"Error 403"]) {
		[myApp addTextToLog:@"You Are Not Permitted To Do This" withCaption:@"cliqset"];
		return YES;
	}
	if ([dataStr isEqualToString:@"Error 404"]) {
		[myApp addTextToLog:@"Item Does Not Exist" withCaption:@"cliqset"];
		return YES;
	}
	
	return NO;
}

// Handle connector errors
- (void)didFailWithError:(NSError *)error {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	// NSString *errorMessage = [@"" stringByAppendingFormat:@"Network connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]];	
	NSString *errorMessage = [@"" stringByAppendingFormat:@"Network connection failed!"];	
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);		
	[myApp addTextToLog:errorMessage withCaption:@"cliqset"];
}

// Events worker thread
-(void)eventThread:(id)data {
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	// Save grabbed events to database, inserting any new ones
	[myApp.database saveEventsToDatabase];
	
	// Again, make sure the in memory array is empty
	[myApp.toEvents removeAllObjects];
	
	// And then, load last 25 from the database.
	[myApp.database loadEventsFromDatabase:myApp.userString];
	
	// Reload events table
	[myApp reloadEventsTable];		
	[myApp showEventsHoverView:NO];
}

// Contact worker thread
-(void)contactThread:(id)data {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	// Make sure we are showing we are busy...
	[myApp showContactsHoverView:YES];
	
	// Write contacts to database
	[myApp.database saveContactsToDatabase];
	
	// Load favorites
	[myApp.database loadFavorites:myApp.userString];
	
	// Clear all in memory, now let's reload from database
	[myApp.contacts removeAllObjects];
	
	// Load contacts from the database
	[myApp.database loadContactsFromDatabase:myApp.userString];
	
	// Reload contacts table
	[myApp reloadContactsTable];
	
	// Reset hover view
	[myApp showContactsHoverView:NO];
	
	// OK... it is safe to allow watchdog to fire now.
	myApp.blockWatchdog = NO;
}

-(void)relationshipImages:(id)id {
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	// Get avatar images
	for (int x=0; x<[myApp.relationships count]; x++) {
		Relationship * relationship = (Relationship *)[myApp.relationships objectAtIndex:x];
		if (relationship.target.avatarBlob == nil && relationship.target.avatarURL!=nil) {
			relationship.target.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: relationship.target.avatarURL]];
			}
		}
	
	[myApp reloadRelationshipsTable];		
	[myApp showRelationshipsHoverView:NO];

	[pool release];
}

// Process background relationship requests
-(void)bgRelationshipRequests:(id)id {

	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	ParsePendingRelationshipsXMLReader *streamingParser7 = [[ParsePendingRelationshipsXMLReader alloc] init];
	NSError *parseError        = nil;	
	
	NSData* data = (NSData*)id;
	
	[myApp.pendingRelationships removeAllObjects];
	
	streamingParser7.mode = 31;
	[streamingParser7 parseXMLFileAtData:data parseError:&parseError];
	
	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.pendingRelationships count]; x++) {
		Target * request = [myApp.pendingRelationships objectAtIndex:x];
		if (request.avatarBlob == nil) {
			request.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: request.avatarURL]]; 
		}
	}		
	
	if ([myApp.pendingRelationships count]>0) {
		[myApp resetPendingRelationships];
		NSString * badge = ([myApp.pendingRelationships count] == 0) ? nil : [@"" stringByAppendingFormat:@"%d", [myApp.pendingRelationships count]];
		[myApp showRelationshipsBadge:badge];
		[myApp reloadProfileTableBG];
		}

	[streamingParser7 release];
	[pool release];
}

// Process background relationship requests
-(void)bgPendingRelationshipRequests:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	ParsePendingRelationshipsXMLReader *streamingParser7 = [[ParsePendingRelationshipsXMLReader alloc] init];
	NSError *parseError        = nil;	
	
	NSData* data = (NSData*)id;

	[myApp.askedForRelationships removeAllObjects];
	
	streamingParser7.mode = 37;
	[streamingParser7 parseXMLFileAtData:data parseError:&parseError];
	
	[streamingParser7 release];
	[pool release];
}

// Process background profile event requests
-(void)bgProfileEventRequests:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	ParseEventXMLReader *streamingParser2                = [[ParseEventXMLReader alloc] init];
	
	NSData * data       = (NSData*)id;
	NSError *parseError = nil;	
	
	[myApp.profileEvents removeAllObjects];
	
	streamingParser2.mode = 119;
	[streamingParser2 parseXMLFileAtData:data parseError:&parseError];
	
	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.profileEvents count]; x++) {
		Event * event = [myApp.profileEvents objectAtIndex:x];
		for (int y=0; y<[event.resources count]; y++) {
			Resource * resource = [event.resources objectAtIndex:y];
			if ([resource.name isEqualToString:@"Thumbnail-1"] ||
				[resource.name isEqualToString:@"Thumbnail-2"] ||
				[resource.name isEqualToString:@"Thumbnail-3"] ||
				[resource.name isEqualToString:@"Thumbnail-4"] ||
				[resource.name isEqualToString:@"Thumbnail-5"]) {
				resource.blob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: resource.value]]; 
				}
			}
		}
	
	[myApp reloadBGRelationshipsTable];	
	[myApp reloadProfileTableBG];	
		
	[streamingParser2 release];
	[pool release];
}

// Process background profile event requests
-(void)ProfileEventRequests:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	ParseEventXMLReader *streamingParser2                = [[ParseEventXMLReader alloc] init];
	
	NSData * data       = (NSData*)id;
	NSError *parseError = nil;	
	
	[myApp.profileEvents removeAllObjects];
	
	streamingParser2.mode = 19;
	[streamingParser2 parseXMLFileAtData:data parseError:&parseError];
	
	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.profileEvents count]; x++) {
		Event * event = [myApp.profileEvents objectAtIndex:x];
		for (int y=0; y<[event.resources count]; y++) {
			Resource * resource = [event.resources objectAtIndex:y];
			if ([resource.name isEqualToString:@"Thumbnail-1"] ||
				[resource.name isEqualToString:@"Thumbnail-2"] ||
				[resource.name isEqualToString:@"Thumbnail-3"] ||
				[resource.name isEqualToString:@"Thumbnail-4"] ||
				[resource.name isEqualToString:@"Thumbnail-5"]) {
				resource.blob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: resource.value]]; 
			}
		}
	}
	
	[myApp reloadProfileTable];	
	
	[streamingParser2 release];
	[pool release];
}

// Process background Get Status requests
-(void)bgGetStatusRequests:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp  = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSError *parseError        = nil;	
	ParseStatusXMLReader *streamingParser3 = [[ParseStatusXMLReader alloc] init];
	
	NSData * data = (NSData*)id;

	// Parse Status
	streamingParser3.mode = 16;
	[streamingParser3 parseXMLFileAtData:data parseError:&parseError];
	
	NSString * status = [NSString stringWithFormat:@"%@", myApp.currentStatus.status];
	[myApp setHomeProfileStatus:(NSString*)status timestamp: myApp.currentStatus.timeStamp];

	[streamingParser3 release];
	[pool release];
}

// Process background Get Messages
-(void)bgGetMessages:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp  = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSError *parseError        = nil;	
	
	ParseMessagesXMLReader *streamingParser6             = [[ParseMessagesXMLReader alloc] init];

	NSData * data = (NSData *)id;
	
	[myApp.messages removeAllObjects];
	
	streamingParser6.mode = 25;
	[streamingParser6 parseXMLFileAtData:data parseError:&parseError];

	[myApp resetUnreadMessages];

	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.messages count]; x++) {
		Message * message = [myApp.messages objectAtIndex:x];
		if (message.sender.avatarBlob == nil) {
			message.sender.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: message.sender.avatarURL]]; 
		}
	}
	
	// Mark badge	
	int badgeCount = 0;
	
	for (int x=0; x<[myApp.messages count]; x++) {
		Message * message = (Message *)[myApp.messages objectAtIndex:x];
		if ([message.read isEqualToString:@"false"]) {badgeCount++;}
	}

	NSString * badge = (badgeCount == 0) ? nil : [@"" stringByAppendingFormat:@"%d", badgeCount];
	[myApp showMessagesBadge:badge];

	[myApp reloadBGMessagesTable];

	[streamingParser6 release];
	[pool release];
}

// Process foreground Get Messages
-(void)fgGetMessages:(id)id {
	
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	cliqsetAppDelegate* myApp  = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	NSError *parseError        = nil;	
	
	ParseMessagesXMLReader *streamingParser6             = [[ParseMessagesXMLReader alloc] init];
	
	NSData * data = (NSData *)id;
	
	[myApp.messages removeAllObjects];
	
	streamingParser6.mode = 25;
	[streamingParser6 parseXMLFileAtData:data parseError:&parseError];
	
	[myApp resetUnreadMessages];
	
	// OK... while we're here, let's populate any picture blobs we might have, too.
	for (int x=0; x<[myApp.messages count]; x++) {
		Message * message = [myApp.messages objectAtIndex:x];
		if (message.sender.avatarBlob == nil) {
			message.sender.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: message.sender.avatarURL]]; 
		}
	}
	
	// Mark badge	
	int badgeCount = 0;
	
	for (int x=0; x<[myApp.messages count]; x++) {
		Message * message = (Message *)[myApp.messages objectAtIndex:x];
		if ([message.read isEqualToString:@"false"]) {badgeCount++;}
	}
	
	NSString * badge = (badgeCount == 0) ? nil : [@"" stringByAppendingFormat:@"%d", badgeCount];
	[myApp showMessagesBadge:badge];
	
	[myApp reloadMessagesTable];
	
	[streamingParser6 release];
	[pool release];
}

-(void)processMessage:(NSData*)data mode:(int)mode {

	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
		
	NSMutableString* workMe;
	NSString *dataStr          = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	NSAutoreleasePool *pool    = [[NSAutoreleasePool alloc] init];			
	NSError *parseError        = nil;	
	
	XMLReader *streamingParser                           = [[XMLReader alloc] init];
	ParseEventXMLReader *streamingParser2                = [[ParseEventXMLReader alloc] init];
	ParseStatusXMLReader *streamingParser3               = [[ParseStatusXMLReader alloc] init];
	ParseProfileXMLReader *streamingParser4              = [[ParseProfileXMLReader alloc] init];
	ParseRelationshipXMLReader *streamingParser5         = [[ParseRelationshipXMLReader alloc] init];
	ParseMessagesXMLReader *streamingParser6             = [[ParseMessagesXMLReader alloc] init];
	ParsePendingRelationshipsXMLReader *streamingParser7 = [[ParsePendingRelationshipsXMLReader alloc] init];
	ParseQueryResultsXMLReader *streamingParser8         = [[ParseQueryResultsXMLReader alloc] init];
	
	if (mode==0 && [dataStr length] < 10) {		
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		[dataStr release];
		myApp.isAuthenticating = YES;
		myApp.isAuthenticated  = NO;
		[myApp flipLoginToFront];
		
		if (myApp.loginString && myApp.passwordString && !([myApp.loginString isEqualToString:@""] && [myApp.passwordString isEqualToString:@""])) {
			[myApp addTextToLog:@"Please re-enter your Username and Password" withCaption:@"Login"];
		}
		
		return;
	}
	
	switch (mode) {
		case 0:
			// Mode 0: get user identifier
			// Extract the user identification string
			workMe          = (NSMutableString*)dataStr;
			workMe          = (NSMutableString*)[[workMe stringByReplacingOccurrencesOfString:@"</UserIdentifier>" withString:@""] stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><UserIdentifier>" withString:@""];
			myApp.userString = workMe;
			
			// Remove splash screen
			if (myApp.splashViewController) {
				[myApp flipSplashToBack];
				myApp.splashViewController = nil;
				}
			
			// Get profile
			ProfileThread * pt = [[[ProfileThread alloc] init] autorelease];
			[pt start];
			
			// Get messages count
			MessageCountThread * mct = [[[MessageCountThread alloc] init] autorelease];
			[mct start];
			
			// Get relationship pending requests
			RelationshipRequestsThread * rrt = [[[RelationshipRequestsThread alloc] init] autorelease];
			[rrt start];
			
			// Get messages
			MessagesThread * mt = [[[MessagesThread alloc] init] autorelease];
			[mt start];
			
			// Get current status
			StatusThread * st = [[[StatusThread alloc] init] autorelease];
			[st start];

			// Load Profile Events
			ProfileEventsThread * pet = [[[ProfileEventsThread alloc] init] autorelease];
			[pet start];
			
			// Load To Events for front page
			EventThread * evt = [[[EventThread alloc] init] autorelease];
			[evt start];
			
			// Load Contacts
			ContactsThread * ct = [[[ContactsThread alloc] init] autorelease];
			[ct start];
			
			// Load Relationships
			RelationshipsThread * rt = [[[RelationshipsThread alloc] init] autorelease];
			[rt start];
			
			myApp.isAuthenticating = NO;
			myApp.isAuthenticated  = YES;
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 1:
			// Mode 1: get a user's contacts
			// Deserialize returned XML
			
			if (![self isError:dataStr]) {

				// Clear contacts array
				[myApp.contacts removeAllObjects];
				
				// Parse Contacts
				[streamingParser parseXMLFileAtData:data parseError:&parseError];
				
				NSString * badge = ([myApp.contacts count] == 0) ? nil : [@"" stringByAppendingFormat:@"%d", [myApp.contacts count]];
				[myApp showContactsBadge:badge];
				
				[NSThread detachNewThreadSelector:@selector(contactThread:) toTarget:self withObject:nil];
							
				// For testing XML deserialization for contacts
				if (0) {
				
				for (int x=0; x<[myApp.contacts count]; x++) {
					Contact *deref = (Contact *)[myApp.contacts objectAtIndex:x];
					NSLog(@"\r\n############");
					NSLog(@"Contact ID : %@", deref.contactIdentifier);
					NSLog(@"Given Name : %@", deref.givenName);
					NSLog(@"Middle Name: %@", deref.middleName);
					NSLog(@"Family Name: %@", deref.familyName);
					NSLog(@"Notes      : %@", deref.notes);
					NSLog(@"Company    : %@", deref.company);
					NSLog(@"Position   : %@", deref.position);
					NSLog(@"____________");
					NSLog(@"Tags");
					for (int y=0; y<[deref.tags count]; y++) {
						if ([[deref.tags objectAtIndex:y] isKindOfClass:[NSString class]]) {
							NSLog(@"%@", [deref.tags objectAtIndex:y]);
						}
						if ([[deref.tags objectAtIndex:y] isKindOfClass:[Tag class]]) {
							Tag * tag = (Tag *)[deref.tags objectAtIndex:y];
							NSLog(@"%@\r\n", tag.tag);
						}
					}
					NSLog(@"____________");
					NSLog(@"Phones");
					for (int y=0; y<[deref.phones count]; y++) {
						if ([[deref.phones objectAtIndex:y] isKindOfClass:[Phone class]]) {
							Phone * phone = (Phone *)[deref.phones objectAtIndex:y];
							NSLog(@"Type    : %@", phone.type);
							NSLog(@"Primary?: %d", phone.primary);
							NSLog(@"Number  : %@\r\n", phone.phoneNumber);
						}
					}
					NSLog(@"____________");
					NSLog(@"URLS");
					for (int y=0; y<[deref.urls count]; y++) {
						if ([[deref.urls objectAtIndex:y] isKindOfClass:[URL class]]) {
							URL * url = (URL *)[deref.urls objectAtIndex:y];
							NSLog(@"Type    : %@", url.type);
							NSLog(@"Primary?: %d", url.primary);
							NSLog(@"URL     : %@\r\n", url.url);
						}
					}
					NSLog(@"____________");
					NSLog(@"Addresses");
					for (int y=0; y<[deref.addresses count]; y++) {
						if ([[deref.addresses objectAtIndex:y] isKindOfClass:[Address class]]) {
							Address * address = (Address *)[deref.addresses objectAtIndex:y];
							NSLog(@"Type       : %@", address.type);
							NSLog(@"Primary?   : %d", address.primary);
							NSLog(@"Street     : %@", address.streetAddress);
							NSLog(@"Locality   : %@", address.locality);
							NSLog(@"Region     : %@", address.region);
							NSLog(@"Country    : %@", address.country);
							NSLog(@"PostalCode : %@\r\n", address.postalCode);
						}
					}
					NSLog(@"____________");
					NSLog(@"Email");
					for (int y=0; y<[deref.emailAddresses count]; y++) {
						if ([[deref.emailAddresses objectAtIndex:y] isKindOfClass:[EmailAddress class]]) {
							EmailAddress * email = (EmailAddress *)[deref.emailAddresses objectAtIndex:y];
							NSLog(@"Type    : %@", email.type);
							NSLog(@"Primary?: %d", email.primary);
							NSLog(@"Email   : %@\r\n", email.address);
						}
					}
					NSLog(@"____________");
					NSLog(@"IM");
					for (int y=0; y<[deref.imScreenNames count]; y++) {
						if ([[deref.imScreenNames objectAtIndex:y] isKindOfClass:[IM class]]) {
							IM * im = (IM *)[deref.imScreenNames objectAtIndex:y];
							NSLog(@"Network : %@", im.network);
							NSLog(@"Primary?: %d", im.primary);
							NSLog(@"Name    : %@\r\n", im.name);
							}
							}
						}
					}				
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			
			break;
			
		case 2:
			// Delete contact
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					
					// Scan through contacts, find the desired object, and remove from in memory array of Contacts.
					for (int x=0; x<[myApp.contacts count]; x++) {
						Contact * contact = (Contact *)[myApp.contacts objectAtIndex:x];
						if ([contact.contactIdentifier isEqualToString:self.currentContact]) {
							[myApp.contacts removeObjectAtIndex:x];
							break;
							}
						}
					
					// Remove contact (and any favorite tagged)
					[myApp.database removeContact:myApp.userString cid:self.currentContact];
					
					// Set filter back to "All"
					[myApp resetSegment];
					
					[myApp reloadContactsTable];
					[myApp showContactsHoverView:NO];
					}
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 3:
			// Delete user email
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database removeEmailAddress:myApp.userString cid:self.currentContact tag:self.currentType];
					}
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 4:
			// Delete user address
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database removeAddress:myApp.userString cid:self.currentContact tag:self.currentType];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 5:
			// Delete user phone
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database removePhone:myApp.userString cid:self.currentContact tag:self.currentType];
				}
			}
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 6:
			// Delete user IM
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database removeIM:myApp.userString cid:self.currentContact tag:self.currentType];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 7:
			// Delete user URL
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database removeURL:myApp.userString cid:self.currentContact tag:self.currentType];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 8:
			
			// Put user phone
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database putPhone:myApp.userString cid:self.currentContact tag:self.currentType content:self.currentField flag:self.currentFlag];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 9:
			
			// Put user url
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database putURL:myApp.userString cid:self.currentContact tag:self.currentType content:self.currentField];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 10:
			
			// Put user email
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database putEmailAddress:myApp.userString cid:self.currentContact tag:self.currentType content:self.currentField flag:self.currentFlag];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 11:
			
			// Put user IM
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database putIM:myApp.userString cid:self.currentContact tag:self.currentType content:self.currentField flag:self.currentFlag];
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 12:
			
			// Put Contact Address
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp.database putAddress:myApp.userString cid:self.currentContact tag:self.currentType street:self.currentStreet locality:self.currentLocality region:self.currentRegion postalCode:self.currentPostalCode country:self.currentCountry];
				}
			}
			
		case 13:
			
			// Put Contact Record
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					if (self.currentContactRecord.contactIdentifier == nil) {
						[myApp.cliqset getUserContacts:myApp.userString reload:NO];
						}
					else {
						[myApp.database putContact:currentContactRecord];
					}
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 14:
			// Get TO events Record
			if (![self isError:dataStr]) {
				
				NSLog(@"To events: %@", dataStr);
				
				// Make sure the array is empty
				[myApp.toEvents removeAllObjects];
				
				streamingParser2.mode = mode;
				[streamingParser2 parseXMLFileAtData:data parseError:&parseError];
			
				// OK... while we're here, let's populate any picture blobs we might have, too.
				for (int x=0; x<[myApp.toEvents count]; x++) {
					Event * event = [myApp.toEvents objectAtIndex:x];
					for (int y=0; y<[event.resources count]; y++) {
						Resource * resource = [event.resources objectAtIndex:y];
						if ([resource.name isEqualToString:@"Thumbnail-1"] ||
							[resource.name isEqualToString:@"Thumbnail-2"] ||
							[resource.name isEqualToString:@"Thumbnail-3"] ||
							[resource.name isEqualToString:@"Thumbnail-4"] ||
							[resource.name isEqualToString:@"Thumbnail-5"]) {
							resource.blob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: resource.value]]; 
						}
					}
				}
				
				NSString * badge = ([myApp.toEvents count] == 0) ? nil : [@"" stringByAppendingFormat:@"%d", [myApp.toEvents count]];
				[myApp showEventsBadge:badge];
				
				[NSThread detachNewThreadSelector:@selector(eventThread:) toTarget:self withObject:nil];
			} else {
				[myApp showEventsHoverView:NO];
			}

			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 15:
			// Get FROM events Record
			if (![self isError:dataStr]) {
				
				// Make sure the array is empty
				[myApp.fromEvents removeAllObjects];
				
				streamingParser2.mode = mode;
				[streamingParser2 parseXMLFileAtData:data parseError:&parseError];
				
				// OK... while we're here, let's populate any picture blobs we might have, too.
				for (int x=0; x<[myApp.fromEvents count]; x++) {
					Event * event = [myApp.fromEvents objectAtIndex:x];
					for (int y=0; y<[event.resources count]; y++) {
						Resource * resource = [event.resources objectAtIndex:y];
						if ([resource.name isEqualToString:@"Thumbnail-1"] ||
							[resource.name isEqualToString:@"Thumbnail-2"] ||
							[resource.name isEqualToString:@"Thumbnail-3"] ||
							[resource.name isEqualToString:@"Thumbnail-4"] ||
							[resource.name isEqualToString:@"Thumbnail-5"]) {
							resource.blob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: resource.value]]; 
						}
					}
				}
				
				// Let's reload the profile table, too.
				// [myApp reloadProfileTableSilent];
				
				// Reload events table
                [myApp reloadEventsTable];		
				[myApp showEventsHoverView:NO];
			} else {
				[myApp showEventsHoverView:NO];
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 16:
			
			// Get Current Status
			if (![dataStr isEqualToString:@"Error 404"]) {
				// Process this in the background
				[NSThread detachNewThreadSelector:@selector(bgGetStatusRequests:) toTarget:self withObject:(NSData*)data];
				}

			break;
			
		case 17:
			
			// Put Current Status
			if (![self isError:dataStr]) {
			}
			
			[myApp showProfileHoverView:NO];
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 18:
			
			// Get Profile
			if (![self isError:dataStr]) {
				// Parse Profile
				[streamingParser4 parseXMLFileAtData:data parseError:&parseError];
				NSString * name = [NSString stringWithFormat:@"%@ %@", myApp.currentProfile.basicProfile.givenName, myApp.currentProfile.basicProfile.familyName];
				[myApp setHomeProfileName:(NSString*)name];
				}
			
			break;
			
		case 119: // Background events
		case 19:
			
			// Get Profile "Profile" Events
			if (![self isError:dataStr]) {
				if (mode==19) {
					[NSThread detachNewThreadSelector:@selector(ProfileEventRequests:) toTarget:self withObject:(NSData*)data];
					}
				else {
					[NSThread detachNewThreadSelector:@selector(bgProfileEventRequests:) toTarget:self withObject:(NSData*)data];
					}
				}
			else {
				[myApp showProfileHoverView:NO];
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 20:
			
			// Get User Relationships
			if (![self isError:dataStr]) {
				[myApp.relationships removeAllObjects];				
				[streamingParser5 parseXMLFileAtData:data parseError:&parseError];
				[NSThread detachNewThreadSelector:@selector(relationshipImages:) toTarget:self withObject:nil];
			} else {
				[myApp showRelationshipsHoverView:NO];
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 21:
		case 35:
			
			// Get Relationship "Relationship" Events
			if (![self isError:dataStr]) {
				
				// Make sure the array is empty
				[myApp.relationshipEvents removeAllObjects];
				
				streamingParser2.mode = mode;
				[streamingParser2 parseXMLFileAtData:data parseError:&parseError];
								
				// OK... while we're here, let's populate any picture blobs we might have, too.
				for (int x=0; x<[myApp.relationshipEvents count]; x++) {
					Event * event = [myApp.relationshipEvents objectAtIndex:x];
					for (int y=0; y<[event.resources count]; y++) {
						Resource * resource = [event.resources objectAtIndex:y];
						if ([resource.name isEqualToString:@"Thumbnail-1"] ||
							[resource.name isEqualToString:@"Thumbnail-2"] ||
							[resource.name isEqualToString:@"Thumbnail-3"] ||
							[resource.name isEqualToString:@"Thumbnail-4"] ||
							[resource.name isEqualToString:@"Thumbnail-5"]) {
							resource.blob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: resource.value]]; 
						}
					}
				}
				
				// Reload events table
                [myApp reloadRelationshipsDetailTable];
				if (self.currentRelationshipOffset >= 0 && mode==21) {
					[myApp slideRelationshipIn:self.currentRelationshipOffset];
					[myApp showRelationshipsDetailHoverView:NO];
					}
				if (self.currentRelationshipOffset >= 0 && mode==35) {
					[myApp slideRelationshipDrillIn:self.currentRelationshipOffset];
					[myApp showRelationshipsDrillHoverView:NO];
					}
				
			} else {
				[myApp showRelationshipsDetailHoverView:NO];
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 22:
			
			// Get Messages Count
			if (![self isError:dataStr]) {
				[myApp resetUnreadMessages];
				}
			
			break;
			
		case 23:
			
			// Get Event Status
			if (![dataStr isEqualToString:@"Error 404"]) {
				// Parse Status
				streamingParser3.mode = mode;
				[streamingParser3 parseXMLFileAtData:data parseError:&parseError];
				NSString * status = [NSString stringWithFormat:@"%@", myApp.eventStatus.status];
				[myApp setEventProfileStatus:(NSString*)status timestamp: myApp.eventStatus.timeStamp];
				}
			break;
		
		case 24:
			
			// Get Relationship Status
			if (![dataStr isEqualToString:@"Error 404"]) {
				// Parse Status
				streamingParser3.mode = mode;
				[streamingParser3 parseXMLFileAtData:data parseError:&parseError];
				NSLog(@"%@", myApp.relationshipStatus);
				NSString * status = [NSString stringWithFormat:@"%@", myApp.relationshipStatus.status];
				
				if (mode == 24) {
					[myApp setRelationshipProfileStatus:(NSString*)status timestamp: myApp.relationshipStatus.timeStamp];
					}
			}
			break;
			
		case 25:
		case 125:
			
			// Get Messages
			if (![self isError:dataStr]) {
				if (mode==25) {
					[NSThread detachNewThreadSelector:@selector(fgGetMessages:) toTarget:self withObject:(NSData*)data];
					}
				if (mode==125) {
					[NSThread detachNewThreadSelector:@selector(bgGetMessages:) toTarget:self withObject:(NSData*)data];
				}
			}
			
			// Get sent messages
			if (mode == 25) {
				SentMessagesThread * mst = [[[SentMessagesThread alloc] init] autorelease];
				[mst start];
				//[myApp showMessagesHoverView:NO];
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			
			break;
			
		case 26:
			
			[myApp showMessagesHoverView:NO];

			// Get Individual Message
			if (![self isError:dataStr]) {
				streamingParser6.mode = mode;
				[streamingParser6 parseXMLFileAtData:data parseError:&parseError];
				
				Message * message = (Message *)[myApp.messages objectAtIndex:self.currentIndex];
				[myApp.database markMessageRead:message.messageIdentifier];
				
				message.read = @"true";
				
				[myApp reloadMessagesTable];

				[myApp slideMessageDetailIn:self.currentIndex];
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			
			break;
			
		case 27:
			// Delete message
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					[myApp showMessagesHoverView:NO];
					[myApp slideMessageDetailOut];

					Message * message = (Message *)[myApp.messages objectAtIndex:self.currentIndex];
					
					// Delete message from the local database
					[myApp.database deleteMessage:message.messageIdentifier];
					
					[myApp.cliqset getMessages];
				}
			}
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 28:
			
			[myApp showMessagesHoverView:NO];
			
			// Get Sent Messages
			if (![self isError:dataStr]) {
				
				streamingParser6.mode = mode;
				[streamingParser6 parseXMLFileAtData:data parseError:&parseError];
				
				// OK... while we're here, let's populate any picture blobs we might have, too.
				for (int x=0; x<[myApp.messages count]; x++) {
					Message * message = [myApp.messages objectAtIndex:x];
					if (message.sender.avatarBlob == nil) {
						message.sender.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: message.sender.avatarURL]]; 
						}
					}				
				}
			
			[myApp reloadBGMessagesTable];
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			
		case 29:
			
			// POST Message
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
				}
			}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 30:
			
			// Get Relationship Requests Count
			if (![self isError:dataStr]) {
				NSMutableString * countString = (NSMutableString*)[[[dataStr stringByReplacingOccurrencesOfString:@"<Count>" withString:@""] stringByReplacingOccurrencesOfString:@"</Count>" withString:@""] stringByReplacingOccurrencesOfString:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" withString:@""];
				myApp.incomingMessagesCount = [countString intValue];
				if (myApp.incomingMessagesCount>0) {
					
					UIView * notification     = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
					UIColor* textColor        = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];	
					
					UIFont* teeny_font        = [UIFont systemFontOfSize:14];
					UIFont* bold_teeny_font   = [UIFont boldSystemFontOfSize:14];
					
					UIImage *graphic          = [UIImage imageNamed:@"user1_information.png"];
					UIImageView *showImage    = [[UIImageView alloc] initWithFrame:CGRectMake(5.0, ((40-(24 * graphic.size.height / graphic.size.width))/2.0), 24, 24 * (graphic.size.height / graphic.size.width))];		
					showImage.image           = graphic;
					
					CGSize constraintSize;
					constraintSize.width      = 250.0f;
					constraintSize.height     = MAXFLOAT;	
					CGSize offsetX1           = [@"You have " sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
					CGSize offsetX2           = [countString sizeWithFont:bold_teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
					CGSize offsetX3           = [@" pending relationship requests" sizeWithFont:teeny_font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeTailTruncation];
					
					UILabel * label1 = [[UILabel alloc] initWithFrame:CGRectMake(34, 10, 200, 20)];
					label1.text      = [NSString stringWithFormat:@"You have "];
					label1.font      = teeny_font;
					label1.textColor = textColor;
					label1.backgroundColor = [UIColor clearColor];
					
					UILabel * label2 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width, 10, offsetX2.width, 20)];
					label2.text      = [NSString stringWithFormat:@"%d", myApp.incomingMessagesCount];
					label2.font      = bold_teeny_font;
					label2.textColor = textColor;
					label2.backgroundColor = [UIColor clearColor];
					
					UILabel * label3 = [[UILabel alloc] initWithFrame:CGRectMake(34 + offsetX1.width + offsetX2.width, 10, offsetX3.width, 20)];
					label3.text      = [NSString stringWithFormat:@" pending relationship requests"];
					label3.font      = teeny_font;
					label3.textColor = textColor;
					label3.backgroundColor = [UIColor clearColor];
					
					[notification addSubview:label1];
					[notification addSubview:label2];
					[notification addSubview:label3];
					[notification addSubview:showImage];
					
					notification.tag = -2;
					
					[myApp.notifications addObject:notification];
					
					[showImage release];
					[label1 release];
					[label2 release];
					[label3 release];
					[notification release];
				}
			}
			
			break;
			
		case 31:
		case 37:
			
			// Get Pending Relationship Requests
			if (![self isError:dataStr]) {
				if (mode == 31) {
					// Process this in the background
					[NSThread detachNewThreadSelector:@selector(bgRelationshipRequests:) toTarget:self withObject:(NSData*)data];
					}
				if (mode == 37) {
					// Process this in the background
					[NSThread detachNewThreadSelector:@selector(bgPendingRelationshipRequests:) toTarget:self withObject:(NSData*)data];
					}
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 32:
			// Delete Relationship
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					}
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;

		case 33:
			// Request Relationship
			if (![self isError:dataStr]) {
				// No body means we are gold
				if ([dataStr length] == 0) {
					}
				}

			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		case 34:
			// Query Results
			if (![self isError:dataStr]) {
				[myApp.queryResults removeAllObjects];
				[streamingParser8 parseXMLFileAtData:data parseError:&parseError];
				
				// OK... while we're here, let's populate any picture blobs we might have, too.
				for (int x=0; x<[myApp.queryResults count]; x++) {
					Profile	* profile = [myApp.queryResults objectAtIndex:x];
					if (profile.basicProfile.avatarBlob == nil && profile.basicProfile.avatarURL != nil) {
						profile.basicProfile.avatarBlob = (NSMutableData*)[NSData dataWithContentsOfURL: [NSURL URLWithString: profile.basicProfile.avatarURL]]; 
						}
					}	
				
				[myApp reloadQueryResultsTable];
				[myApp showQueryResultsHoverView:NO];
				}
			
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
			
		default:
			[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
			break;
	}
	
	[streamingParser8 release]; 
	[streamingParser7 release]; 
	[streamingParser6 release]; 
	[streamingParser5 release]; 
	[streamingParser4 release]; 
	[streamingParser3 release]; 
	[streamingParser2 release]; 
	[streamingParser release]; 
	
	[dataStr release];
	[pool release];
}

// Get all user's updated since ISO8601 date
-(void)getUserContacts:(NSString*)userid since:(NSString*)since {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 14;
	connector.parent = self;
	
	NSLog(@"%@", [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts?start=0&count=1000&updatedsince=%@", myApp.userString, since]);
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts?start=0&count=1000&updatedsince=%@", myApp.userString, since]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[myApp showContactsHoverView:YES];
	[myApp showEventsHoverView:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}	
}

// Get user contacts
-(void)getUserContacts:(NSString*)userid reload:(BOOL)reload {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];

	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 1;
	connector.parent = self;
	
	NSString * url;
	if (([myApp.database countContactsFromDatabase] == 0) || (reload == YES)) {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts?start=0&count=1000", myApp.userString];
		//url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts?start=0&count=20&updatedsince=%@", myApp.userString, @"2009-01-01T00:00:00.000Z"];
		} 
	else {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts?start=0&count=1000&updatedsince=%@", myApp.userString, [myApp.database getLatestContactDateFromDatabase]];
		}
	
	NSLog(@"get contacts url: %@", url);
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[myApp showContactsHoverView:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}	
}

// Delete a user's contact
-(void)deleteUserContact:(NSString*)cid isFavorite:(BOOL)favorite {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	// Show busy indicator
	if (favorite) {
		[myApp showFavoritesHoverView];
	}
	else {
		[myApp showContactsHoverView:YES];
	}
	
	self.isFavorite = favorite;
	
	self.currentContact = (NSMutableString*)cid;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@", myApp.userString, cid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 2;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Delete an email address by type
-(void)deleteUserEmail:(NSString*)cid tag:(NSString*)tag {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/emailaddresses/%@", myApp.userString, cid, tag];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 3;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Delete an address by type
-(void)deleteUserAddress:(NSString*)cid tag:(NSString*)tag {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/addresses/%@", myApp.userString, cid, tag];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 4;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Delete a phone by type
-(void)deleteUserPhone:(NSString*)cid tag:(NSString*)tag {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/phones/%@", myApp.userString, cid, tag];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 5;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Delete an IM by type
-(void)deleteUserIM:(NSString*)cid tag:(NSString*)tag {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/ims/%@", myApp.userString, cid, tag];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 6;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Delete an URL by type
-(void)deleteUserURL:(NSString*)cid tag:(NSString*)tag {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/urls/%@", myApp.userString, cid, tag];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 7;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

-(NSString*)xmlEncode:(NSString*)target {
	NSMutableString * work = [[target copy] autorelease];

	work = (NSMutableString*)[work stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"];
	work = (NSMutableString*)[work stringByReplacingOccurrencesOfString:@"<" withString:@"&lt;"];
	work = (NSMutableString*)[work stringByReplacingOccurrencesOfString:@">" withString:@"&gt;"];
	work = (NSMutableString*)[work stringByReplacingOccurrencesOfString:@"'" withString:@"&apos;"];
	work = (NSMutableString*)[work stringByReplacingOccurrencesOfString:@"\"" withString:@"&quot;"];
	
	return work;
}

// Put a phone record
-(void)putPhone:(NSString*)cid tag:(NSString*)tag number:(NSString*)number primary:(BOOL)primary {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	self.currentField   = (NSMutableString*)number;
	self.currentFlag    = (BOOL)primary;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/phones/%@", myApp.userString, cid, tag];
	
	NSString *primaryString = primary ? @"true" : @"false";
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Phone><Type>%@</Type><PhoneNumber>%@</PhoneNumber><Primary>%@</Primary></Phone>", [self xmlEncode:tag], [self xmlEncode:number], [self xmlEncode:primaryString]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 8;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put an url record
-(void)putURL:(NSString*)cid tag:(NSString*)tag number:(NSString*)number primary:(BOOL)primary {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	self.currentField   = (NSMutableString*)number;
	self.currentFlag    = (BOOL)primary;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/urls/%@", myApp.userString, cid, tag];
	
	NSString *primaryString = primary ? @"true" : @"false";
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><URL><Type>%@</Type><URL>%@</URL><Primary>%@</Primary></URL>", [self xmlEncode:tag], [self xmlEncode:number], [self xmlEncode:primaryString]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 9;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put an email record
-(void)putEmail:(NSString*)cid tag:(NSString*)tag number:(NSString*)number primary:(BOOL)primary {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	self.currentField   = (NSMutableString*)number;
	self.currentFlag    = (BOOL)primary;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/emailaddresses/%@", myApp.userString, cid, tag];
	
	NSString *primaryString = primary ? @"true" : @"false";
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><EmailAddress><Type>%@</Type><Address>%@</Address><Primary>%@</Primary></EmailAddress>", [self xmlEncode:tag], [self xmlEncode:number], [self xmlEncode:primaryString]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 10;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put an IM record
-(void)putIM:(NSString*)cid tag:(NSString*)tag number:(NSString*)number primary:(BOOL)primary {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact = (NSMutableString*)cid;
	self.currentType    = (NSMutableString*)tag;
	self.currentField   = (NSMutableString*)number;
	self.currentFlag    = (BOOL)primary;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/ims/%@", myApp.userString, cid, tag];
	
	NSString *primaryString = primary ? @"true" : @"false";
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><IM><Network>%@</Network><Name>%@</Name><Primary>%@</Primary></IM>", [self xmlEncode:tag], [self xmlEncode:number], [self xmlEncode:primaryString]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 11;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put an Address record
-(void)putAddress:(NSString*)cid tag:(NSString*)tag street:(NSString*)street locality:(NSString*)locality region:(NSString*)region postalCode:(NSString*)postalCode country:(NSString *)country {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContact    = (NSMutableString*)cid;
	self.currentType       = (NSMutableString*)tag;
	self.currentStreet     = (NSMutableString*)street;
	self.currentLocality   = (NSMutableString*)locality;
	self.currentRegion     = (NSMutableString*)region;
	self.currentPostalCode = (NSMutableString*)postalCode;
	self.currentCountry    = (NSMutableString*)country;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@/addresses/%@", myApp.userString, cid, tag];
		
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Address><Type>%@</Type><Primary>true</Primary><StreetAddress>%@</StreetAddress><Locality>%@</Locality><Region>%@</Region><Country>%@</Country><PostCode>%@</PostCode></Address>", [self xmlEncode:tag], [self xmlEncode:street], [self xmlEncode:locality], [self xmlEncode:region], [self xmlEncode:country], [self xmlEncode:postalCode]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 12;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put a Contact record
-(void)putContact:(Contact*)contact {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	self.currentContactRecord = contact;
	
	NSString *url;
	if (contact.contactIdentifier != nil) {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts/%@", myApp.userString, contact.contactIdentifier];
	  }
	else {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/contacts", myApp.userString];
	}
	
	NSLog(@"%@", url);

	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	// Start constructing contact record.
	NSMutableString* data = @"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Contact>";
	
	data = (NSMutableString*)[data stringByAppendingFormat:@"<GivenName>%@</GivenName>", [self xmlEncode:contact.givenName == nil ? @"" : contact.givenName]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<MiddleName>%@</MiddleName>", [self xmlEncode:contact.middleName == nil ? @"" : contact.middleName]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<FamilyName>%@</FamilyName>", [self xmlEncode:contact.familyName == nil ? @"" : contact.familyName]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<Notes>%@</Notes>", [self xmlEncode:contact.notes == nil ? @"" : contact.notes]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<Company>%@</Company>", [self xmlEncode:contact.company == nil ? @"" : contact.company]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<Position>%@</Position>", [self xmlEncode:contact.position == nil ? @"" : contact.position]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<PhotoUrl>%@</PhotoUrl>", [self xmlEncode:contact.photoURL == nil ? @"" : contact.photoURL]];

	if ([contact.emailAddresses count]>0) {
	// Build email addresses
	data = (NSMutableString*)[data stringByAppendingString:@"<EmailAddresses>"];
	for (int x=0; x<[contact.emailAddresses count]; x++) {
		data = (NSMutableString*)[data stringByAppendingString:@"<EmailAddress>"];
		EmailAddress * email = (EmailAddress *)[contact.emailAddresses objectAtIndex:x];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Type>%@</Type>", [self xmlEncode:email.type == nil ? @"" : email.type]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Address>%@</Address>", [self xmlEncode:email.address == nil ? @"" : email.address]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Primary>%@</Primary>", (email.primary == 0) ? @"false" : @"true"];
		data = (NSMutableString*)[data stringByAppendingString:@"</EmailAddress>"];
	}
	data = (NSMutableString*)[data stringByAppendingString:@"</EmailAddresses>"];
	}
	
	if ([contact.addresses count]>0) {
	// Build Addresses
	data = (NSMutableString*)[data stringByAppendingString:@"<Addresses>"];
	for (int x=0; x<[contact.addresses count]; x++) {
		data = (NSMutableString*)[data stringByAppendingString:@"<Address>"];
		Address * address = (Address *)[contact.addresses objectAtIndex:x];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Type>%@</Type>", [self xmlEncode:address.type == nil ? @"" : address.type]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Primary>%@</Primary>", (address.primary == 0) ? @"false" : @"true"];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<StreetAddress>%@</StreetAddress>", [self xmlEncode:address.streetAddress == nil ? @"" : address.streetAddress]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Locality>%@</Locality>", [self xmlEncode:address.locality == nil ? @"" : address.locality]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Region>%@</Region>", [self xmlEncode:address.region == nil ? @"" : address.region]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<PostCode>%@</PostCode>", [self xmlEncode:address.postalCode == nil ? @"" : address.postalCode]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Country>%@</Country>", [self xmlEncode:address.country == nil ? @"" : address.country]];
		data = (NSMutableString*)[data stringByAppendingString:@"</Address>"];
	}
	data = (NSMutableString*)[data stringByAppendingString:@"</Addresses>"];
	}
		
	if ([contact.imScreenNames count]>0) {
	// Build IMs
	data = (NSMutableString*)[data stringByAppendingString:@"<IMs>"];
	for (int x=0; x<[contact.imScreenNames count]; x++) {
		data = (NSMutableString*)[data stringByAppendingString:@"<IM>"];
		IM * im = (IM *)[contact.imScreenNames objectAtIndex:x];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Network>%@</Network>", im.network == nil ? @"" : [[[[[[im.network stringByReplacingOccurrencesOfString:@"Aim" withString:@"AIM" ] stringByReplacingOccurrencesOfString:@"Gtalk" withString:@"GTalk"] stringByReplacingOccurrencesOfString:@"Icq" withString:@"ICQ"] stringByReplacingOccurrencesOfString:@"Xmpp" withString:@"XMPP"] stringByReplacingOccurrencesOfString:@"Qq" withString:@"QQ"] stringByReplacingOccurrencesOfString:@"Msn" withString:@"MSN"]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Name>%@</Name>", [self xmlEncode:im.name == nil ? @"" : im.name]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Primary>%@</Primary>", (im.primary == 0) ? @"false" : @"true"];
		data = (NSMutableString*)[data stringByAppendingString:@"</IM>"];
	}
	data = (NSMutableString*)[data stringByAppendingString:@"</IMs>"];
	}
	
	if ([contact.phones count]>0) {
	// Build Phones
	data = (NSMutableString*)[data stringByAppendingString:@"<Phones>"];
	for (int x=0; x<[contact.phones count]; x++) {
		data = (NSMutableString*)[data stringByAppendingString:@"<Phone>"];
		Phone * phone = (Phone *)[contact.phones objectAtIndex:x];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Type>%@</Type>", [self xmlEncode:phone.type == nil ? @"" : phone.type]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<PhoneNumber>%@</PhoneNumber>", [self xmlEncode:phone.phoneNumber == nil ? @"" : phone.phoneNumber]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Primary>%@</Primary>", (phone.primary == 0) ? @"false" : @"true"];
		data = (NSMutableString*)[data stringByAppendingString:@"</Phone>"];
	}
	data = (NSMutableString*)[data stringByAppendingString:@"</Phones>"];
	}
	
	if ([contact.urls count]>0) {
	// Build URLs
	data = (NSMutableString*)[data stringByAppendingString:@"<URLs>"];
	for (int x=0; x<[contact.urls count]; x++) {
		data = (NSMutableString*)[data stringByAppendingString:@"<URL>"];
		URL * url = (URL *)[contact.urls objectAtIndex:x];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Type>%@</Type>", [self xmlEncode:url.type == nil ? @"" : url.type]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<URL>%@</URL>", [self xmlEncode:url.url == nil ? @"" : url.url]];
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Primary>%@</Primary>", (url.primary == 0) ? @"false" : @"true"];
		data = (NSMutableString*)[data stringByAppendingString:@"</URL>"];
	}
	data = (NSMutableString*)[data stringByAppendingString:@"</URLs>"];
	}
	
	//if ([contact.tags count]>0) {
		data = (NSMutableString*)[data stringByAppendingString:@"<Tags>"];
		for (int x=0; x<[contact.tags count]; x++) {
			data = (NSMutableString*)[data stringByAppendingString:@"<Tag>"];
			Tag * tag = (Tag *)[contact.tags objectAtIndex:x];
			data = (NSMutableString*)[data stringByAppendingFormat:@"<Tag>%@</Tag>", [self xmlEncode:tag.tag == nil ? @"" : tag.tag]];
			data = (NSMutableString*)[data stringByAppendingString:@"</Tag>"];
		}
		data = (NSMutableString*)[data stringByAppendingString:@"</Tags>"];
	//}
	
	// Cap off the contact element
	data = (NSMutableString*)[data stringByAppendingString:@"</Contact>"];
	
	NSLog(@"%@", data);
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 13;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	if (contact.contactIdentifier!=nil) {
		[connector.theRequest setHTTPMethod:@"PUT"];
		} 
	else {
		[connector.theRequest setHTTPMethod:@"POST"];
	}
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Load up events array
-(void)loadToEvents {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSString *url;
	
	if (myApp.userString == nil) {return;}

	if ([myApp.database countEventsFromDatabase] == 0) {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/to?count=25", myApp.userString];
	} else {
		url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/to?count=25&createdsince=%@", myApp.userString, [myApp.database getLatestEventDateFromDatabase]];
	}
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 14;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showEventsHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];				
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Load up From events array
-(void)loadFromEvents:(NSString*)uid reload:(BOOL)reload {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/from?count=10", uid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 15;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showEventsHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}	
}

// Load up Profile events array
-(void)loadProfileEvents:(NSString*)uid reload:(BOOL)reload {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/from?count=10", uid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 19;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showProfileHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}	
}

// Load up Profile events array
-(void)loadProfileEventsBG:(NSString*)uid reload:(BOOL)reload {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/from?count=10", uid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 119;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Load up Relationship events array
-(void)loadRelationshipEvents:(NSString*)uid offset:(int)offset {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/from?count=10", uid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 21;
	connector.parent = self;
	
	self.currentRelationshipOffset = offset;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showRelationshipsDetailHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Load up Relationship Drill events array
-(void)loadRelationshipDrillEvents:(NSString*)uid offset:(int)offset {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/events/from?count=10", uid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 35;
	connector.parent = self;
	
	self.currentRelationshipOffset = offset;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showRelationshipsDetailHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get current status
-(void)getCurrentStatus {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/status", myApp.userString];

	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 16;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	//[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Put current status
-(void)putCurrentStatus:(NSString*)status {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	myApp.currentStatus.status = (NSMutableString *)status;
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/status", myApp.userString];

	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 17;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Status>%@</Status>", [self xmlEncode:status]];
	
	//[work release];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	[myApp showProfileHoverView:YES];
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}
}

// Get user profile
-(void)getProfile {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/profile", myApp.userString];

	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 18;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
		} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
		}	
}

// Get user relationships
-(void)getRelationships {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 20;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get messages count
-(void)getMessagesCount {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/to/count?read=false", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 22;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get event status
-(void)getEventStatus:(NSString*)userid {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/status", userid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 23;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Get relationship status
-(void)getRelationshipStatus:(NSString*)userid {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/status", userid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 24;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Get messages
-(void)getMessages {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/to?count=30", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 25;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[myApp showMessagesHoverView:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Get messages
-(void)getBGMessages {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/to?count=30", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 125;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Get message
-(void)getMessage:(NSString*)messageID messageIndex:(int)index {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/to/%@", myApp.userString, messageID];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 26;
	connector.parent = self;
	
	self.currentIndex = index;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Delete message
-(void)deleteMessage:(NSString*)messageID messageIndex:(int)index {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/to/%@", myApp.userString, messageID];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 27;
	connector.parent = self;
	
	self.currentIndex = index;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get Sent messages
-(void)getSentMessages {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages/from", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 28;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[myApp showMessagesHoverView:YES];
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Send a message to one or more recipients
-(void)sendMessage:(NSString*)subject message:(NSString*)body recipients:(NSArray*)recipients {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/messages", myApp.userString];
	
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Message><MessageEnvelope>"];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<Subject>%@</Subject>",                       [self xmlEncode:subject]];
	data = (NSMutableString*)[data stringByAppendingFormat:@"<Recipients>"];
	
	for (int x=0; x<[recipients count]; x++) {
		data = (NSMutableString*)[data stringByAppendingFormat:@"<Recipient>%@</Recipient>", [self xmlEncode:[recipients objectAtIndex:x]]];
		}
	
	data = (NSMutableString*)[data stringByAppendingFormat:@"</Recipients>"];
	data = (NSMutableString*)[data stringByAppendingFormat:@"</MessageEnvelope><Body>%@</Body></Message>", [self xmlEncode:body]];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 29;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"POST"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Get relationship requests count
-(void)getRelationshipRequestsCount {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships/requests/to/count", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 30;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get relationship requests 
-(void)getRelationshipRequests {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships/requests/to", myApp.userString];
	
	// Connector * connector = [[[Connector alloc] init] autorelease];
	Connector * connector = [[[Connector alloc] init] retain];
	
	connector.mode   = 31;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Get asked fro relationship requests 
-(void)getAskedForRelationshipRequests {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships/requests/from", myApp.userString];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 37;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Delete relationship
-(void)deleteRelationship:(NSString*)userid {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships/%@", myApp.userString, userid];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 32;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"DELETE"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Request relationship
-(void)requestRelationship:(NSString*)userid {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/%@/relationships/%@", myApp.userString, userid];
		
	NSMutableString * data = (NSMutableString*)[@"" stringByAppendingFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Tags></Tags>"];
	
	NSData* formData = [data dataUsingEncoding:NSASCIIStringEncoding];
	NSInteger dataLength = [formData length];
	NSString* dataLengthStr = [NSString stringWithFormat:@"%d", dataLength];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 33;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"PUT"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	[connector.theRequest addValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	[connector.theRequest addValue:@"api.cliqset.com" forHTTPHeaderField:@"Host"];
	[connector.theRequest addValue:dataLengthStr forHTTPHeaderField:@"Content-Length"];
    [connector.theRequest setHTTPBody:(NSData*)formData];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}
}

// Query Cliqset 
-(void)query:(NSString*)query {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if (myApp.userString == nil) {return;}
	NSString *url = [@"" stringByAppendingFormat:@"https://api.cliqset.com/user/search/basic?q=%@&start=0&count=10", query];
	
	Connector * connector = [[[Connector alloc] init] autorelease];
	
	connector.mode   = 34;
	connector.parent = self;
	
	connector.theRequest=(NSMutableURLRequest*)[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];	
	
	[connector.theRequest setHTTPMethod:@"GET"];
	
	[connector.theRequest addValue:myApp.authenticationString forHTTPHeaderField:@"Authorization"];
	[connector.theRequest addValue:consumerKey forHTTPHeaderField:@"CliqsetConsumerKey"];
	
	connector.theConnection=[[NSURLConnection alloc] initWithRequest:connector.theRequest delegate:connector];
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	
	if (connector.theConnection) {
		connector.receivedData=[[NSMutableData data] retain];		
	} 
	else {
		[myApp addTextToLog:@"Could not connect to the network" withCaption:@"cliqset"];
	}	
}

// Release cliqset
-(void)dealloc {
	[currentContactRecord release];
	[currentStreet release];
	[currentLocality release];
	[currentRegion release];
	[currentPostalCode release];
	[currentCountry release];
	
	[currentContact release];
	[currentType release];
	[super dealloc];
}

@end
